package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.CookieData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.DBAdapter;
import bsi.vn.Lib.ProcessFunc;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class SettingActivity extends Activity {
	private DBAdapter dbAdapter;
	private View mSettingStatusView;
	private View mSettingFormView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		// Show the Up button in the action bar.
		//setupActionBar();
		
		findViewById(R.id.stbtInitData).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						myAsyncTask myWebFetch = new myAsyncTask();
		                myWebFetch.execute();
					}
				});
		
		findViewById(R.id.stbtLogout).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						myAsyncTaskLogout myLogout = new myAsyncTaskLogout();
		                myLogout.execute();
					}
				});
	}
	
private class myAsyncTask extends AsyncTask<String, String, String>    {
    	
    @Override 	
	protected String doInBackground(String... params) {
    	CookieData loc_cCookie = ProcessFunc.GetCookie(SettingActivity.this);
    	int loc_iUserId = loc_cCookie.getUserId();
    	String loc_sCookie = loc_cCookie.getCookie();
    	GetErrorList(loc_iUserId, loc_sCookie);
    	GetErrorDetail(loc_iUserId, loc_sCookie);
    	GetProvince(loc_iUserId, loc_sCookie);
    	GetCustomer(loc_iUserId, loc_sCookie);
		return "0";
	}
		
		@Override
		protected void onPostExecute(String result) {
			if (result == "0")
				ProcessFunc.ShowSimpleDialog(SettingActivity.this, "Notice", "Initial data finish!");
		}
		
        @Override
        protected void onPreExecute() {
         }
        
        @Override 
        protected void onProgressUpdate(String... text) {
        }
 	} 

private class myAsyncTaskLogout extends AsyncTask<String, String, String>    {
	
    @Override 	
	protected String doInBackground(String... params) {
    	InputStream is = null;
    	
		try
		{
			CookieData loc_cCookie = ProcessFunc.GetCookie(SettingActivity.this);
			StringBuilder sb = new StringBuilder();
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
            
			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_LOGOUT));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(loc_cCookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, loc_cCookie.getCookie()));
	            
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				return sb.toString();
			}
			catch(Exception e){
				Log.e("test", "Error converting result "+e.toString());
			}
		} 
		catch (ClientProtocolException  e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
		
		@Override
		protected void onPostExecute(String result) {
			String sResponse[] = result.split("\\|");
			if (sResponse.length <= 0)
			{
				ProcessFunc.ShowSimpleDialog(SettingActivity.this, "Error", "Logout error.");
				return;
			}
			if (Integer.parseInt(sResponse[0]) != 0)
			{
				ProcessFunc.ShowSimpleDialog(SettingActivity.this, "Error", sResponse[1]);
				return;
			}
			Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
			startActivity(intent);
		}
		
        @Override
        protected void onPreExecute() {
        }
        
        @Override
        protected void onProgressUpdate(String... text) {
        }
 	}

	private void GetErrorList(int userid, String cookie)
	{
		InputStream is = null;
		try
		{
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
            
			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_ERRORLIST));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(userid)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie));
	            
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String sResponse[] = sb.toString().split("\\|");
				if (sResponse.length <= 0)
				{
					Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
					return;
				}
				if (Integer.parseInt(sResponse[0]) != 0)
				{
					Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
					return;
				}
				try{
					JSONArray jArray = new JSONArray(sResponse[1]);
					dbAdapter = new DBAdapter(SettingActivity.this);
					dbAdapter.open();
					dbAdapter.deleteTable(Consts.TABLE_ERRORLIST);
					long insertFlag = 0;
					for(int i=0;i<jArray.length();i++){
						JSONObject json_data = jArray.getJSONObject(i);
						insertFlag = dbAdapter.insertErrorListTbl(json_data.getInt(Consts.SDB_ERRORID), json_data.getString(Consts.SDB_ERRORCODE), json_data.getString(Consts.SDB_DESCRIPTION));
						if (insertFlag <= 0) insertFlag = 1;
					}
					if (insertFlag == 1)
					{
						Toast.makeText(SettingActivity.this, "Update error list error.", Toast.LENGTH_SHORT).show();
						return;	    			
					}
					dbAdapter.close();
				}
				catch(JSONException e){
					Log.e("log_tag", "Error parsing data "+e.toString());
				}
			}
			catch(Exception e){
				Log.e("test", "Error converting result "+e.toString());
			}
		} 
		catch (ClientProtocolException  e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void GetErrorDetail(int userid, String cookie)
	{
		InputStream is = null;
		try
		{
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
            
			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_ERRORDETAIL));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(userid)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie));
	            
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String sResponse[] = sb.toString().split("\\|");
				if (sResponse.length <= 0)
				{
					Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
					return;
				}
				if (Integer.parseInt(sResponse[0]) != 0)
				{
					Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
					return;
				}
				try{
					JSONArray jArray = new JSONArray(sResponse[1]);
					dbAdapter = new DBAdapter(SettingActivity.this);
					dbAdapter.open();
					dbAdapter.deleteTable(Consts.TABLE_ERRORDETAIL);
					long insertFlag = 0;
					for(int i=0;i<jArray.length();i++){
						JSONObject json_data = jArray.getJSONObject(i);
						insertFlag = dbAdapter.insertErrorDetailTbl(json_data.getInt(Consts.SDB_ERRORDETAILID), json_data.getInt(Consts.SDB_ERRORID), 
										json_data.getInt(Consts.SDB_ORDER), json_data.getString(Consts.SDB_DESCRIPTION));
						if (insertFlag <= 0) insertFlag = 1;
					}
					if (insertFlag == 1)
					{
						Toast.makeText(SettingActivity.this, "Update error detail error.", Toast.LENGTH_SHORT).show();
						return;	    			
					}
					dbAdapter.close();
				}
				catch(JSONException e){
					Log.e("log_tag", "Error parsing data "+e.toString());
				}
		    //return sb.toString();
			}
			catch(Exception e){
				Log.e("test", "Error converting result "+e.toString());
			}
		} 
		catch (ClientProtocolException  e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void GetProvince(int userid, String cookie)
	{
		InputStream is = null;
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
	            
		    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
		    nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_PROVINCE));
		    nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(userid)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie));
		            
		    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		    HttpResponse response = httpClient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
		    is = entity.getContent();
		    try{
		    	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
			    StringBuilder sb = new StringBuilder();
			    String line = null;
			    while ((line = reader.readLine()) != null) {
			    	sb.append(line + "\n");
			    }
			    is.close();
			    String sResponse[] = sb.toString().split("\\|");
			    if (sResponse.length <= 0)
				{
			    	Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
			    	return;
				}
			    if (Integer.parseInt(sResponse[0]) != 0)
				{
			    	Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
			    	return;
				}
			    try{
		    		JSONArray jArray = new JSONArray(sResponse[1]);
		    		dbAdapter = new DBAdapter(SettingActivity.this);
		    		dbAdapter.open();
		    		dbAdapter.deleteTable(Consts.TABLE_PROVINCE);
		    		long insertFlag = 0;
		    		for(int i=0;i<jArray.length();i++){
		    			JSONObject json_data = jArray.getJSONObject(i);
		    			insertFlag = dbAdapter.insertProvinceTbl(json_data.getInt(Consts.SDB_PROVINCEID), json_data.getString(Consts.SDB_NAME));
		    			if (insertFlag <= 0) insertFlag = 1;
		    		}
		    		if (insertFlag == 1)
		    		{
		    			Toast.makeText(SettingActivity.this, "Update province data error.", Toast.LENGTH_SHORT).show();
				    	return;	    			
		    		}
		    		dbAdapter.close();
		    	}
		    	catch(JSONException e){
		    		Log.e("log_tag", "Error parsing data "+e.toString());
		    	}
			    //return sb.toString();
		    }
			catch(Exception e){
			   	Log.e("test", "Error converting result "+e.toString());
			}
		} 
		catch (ClientProtocolException  e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void GetCustomer(int userid, String cookie)
	{
		InputStream is = null;
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
	                
		            
		    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
		    nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_CUSTOMER));
		    nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(userid)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie));
		    
		    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		    HttpResponse response = httpClient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
		    is = entity.getContent();
		    
		    try{
		    	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
			    StringBuilder sb = new StringBuilder();
			    String line = null;
			    while ((line = reader.readLine()) != null) {
			    	sb.append(line + "\n");
			    }
			    is.close();
			    String sResponse[] = sb.toString().split("\\|");
			    if (sResponse.length <= 0)
				{
			    	Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
			    	return;
				}
			    if (Integer.parseInt(sResponse[0]) != 0)
				{
			    	Toast.makeText(SettingActivity.this, "Get data from server error.", Toast.LENGTH_SHORT).show();
			    	return;
				}
			    try{
		    		JSONArray jArray = new JSONArray(sResponse[1]);
		    		dbAdapter = new DBAdapter(SettingActivity.this);
		    		dbAdapter.open();
		    		dbAdapter.deleteTable(Consts.TABLE_CUSTOMER);
		    		long insertFlag = 0;
		    		for(int i=0;i<jArray.length();i++){
		    			JSONObject json_data = jArray.getJSONObject(i);
		    			insertFlag = dbAdapter.insertCustomerTbl(json_data.getInt(Consts.SDB_CUSTOMERID), json_data.getString(Consts.SDB_NAME));
		    			if (insertFlag <= 0) insertFlag = 1;
		    		}
		    		if (insertFlag == 1)
		    		{
		    			Toast.makeText(SettingActivity.this, "Update customer data error.", Toast.LENGTH_SHORT).show();
				    	return;	    			
		    		}
		    		dbAdapter.close();
		    	}
		    	catch(JSONException e){
		    		Log.e("log_tag", "Error parsing data "+e.toString());
		    	}
			    //return sb.toString();
		    }
			catch(Exception e){
			   	Log.e("test", "Error converting result "+e.toString());
			}
		} 
		catch (ClientProtocolException  e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
//	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
//	private void setupActionBar() {
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//			getActionBar().setDisplayHomeAsUpEnabled(true);
//		}
//	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		 MenuInflater menuInflater = getMenuInflater();
	        menuInflater.inflate(R.menu.atmsearch, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() != R.id.menu_sub && item.getItemId() != R.id.menu_setting){
			startActivity(ProcessFunc.MenuAction(this, item));
		}
		return true;
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mSettingStatusView.setVisibility(View.VISIBLE);
			mSettingStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mSettingStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mSettingFormView.setVisibility(View.VISIBLE);
			mSettingFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mSettingFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		}
	}

}
